const Router = require('koa-router')

const apiRouter = new Router({
  prefix: '/api'
})

const validateUser = async (ctx, next) => {
  if (!ctx.session.user) {
    ctx.status = 401
    ctx.body = 'need login'
  } else {
    await next()
  }
}

apiRouter.use(validateUser)

// 返回固定格式
const successResponse = (data) => {
  return {
    success: true,
    data
  }
}

apiRouter
  .get('/courses', async (ctx) => {
    const courses = await ctx.db.getAllCourses()
    ctx.body = successResponse(courses)
  })

module.exports = apiRouter
